package com.anabur.bean.abstracts;

import java.io.IOException;
import java.io.Serializable;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import javax.xml.bind.ValidationException;

import com.anabur.bean.LoginBean;

public abstract class AbstractBean implements Serializable{
	
	private static final long serialVersionUID = 1L;
	public final static String FORMAT_DATE = "dd/MM/yyyy";
	public final static String LOGGED_IN = "LOGGED_IN";
	public final static String USER_LOG_NAME = "USER_LOG_NAME";
	public static final String SUCCESS = "SUCCESS";
	public static final String ERROR = "ERROR";
	
	private String userLoggedname;
	
	public String getUserLoggedname() {
		return userLoggedname;
	}

	public void setUserLoggedname(String userLoggedname) {
		this.userLoggedname = userLoggedname;
	}
	
	public AbstractBean(){
		ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
		Map<String, Object> sessionMap = externalContext.getSessionMap();
		if(!this.getClass().equals(LoginBean.class)
				&& (sessionMap.get(LOGGED_IN) == null || !(Boolean)sessionMap.get(LOGGED_IN))){
			try {
				externalContext.redirect("login.xhtml");
			} catch (IOException e) {
				logErrorInPopupWithoutDetail(e);
			}
		} else {
			setUserLoggedname((String)sessionMap.get(USER_LOG_NAME));
		}
	}

	public void logErrorInPopupWithoutDetail(ValidationException e){
		FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), "");
        FacesContext.getCurrentInstance().addMessage(null, msg);
        e.printStackTrace();
	}
	
	public void logWarnInPopupWithoutDetail(String error){
		FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_WARN, error, "");
        FacesContext.getCurrentInstance().addMessage(null, msg);
	}
	
	public void logErrorInPopupWithoutDetail(String error){
		FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, error, "");
        FacesContext.getCurrentInstance().addMessage(null, msg);
	}
	
	public void logErrorInPopupWithoutDetail(Exception e){
		FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, e.toString(), "");
        FacesContext.getCurrentInstance().addMessage(null, msg);
	}
	
	public void closeSession(){
		FacesContext context = FacesContext.getCurrentInstance();
		ExternalContext externalContext = context.getExternalContext();
		Object session = externalContext.getSession(false);
		HttpSession httpSession = (HttpSession) session;
		httpSession.invalidate();
	}
}
